package com.ai.util;

import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取视频回放路径
 * @Author jiaok
 * @Date 2024-01-02 9:47
 */
@Slf4j
public class GetCameraPlaybackUrlUtil {

    public static String getCameraPlaybackUrl(String cameraIndexCode,String alarmTime){
        String urlJson = GetCameraPlaybackUrlUtil.getPlaybackUrl(cameraIndexCode,alarmTime);
        log.info("===========================  平台返回结果：{}  ===========================",urlJson);
        JSONObject jsonObject = JSONObject.parseObject(urlJson);
        JSONObject msg = (JSONObject) jsonObject.get("data");
        String rtspUrl = (String) msg.get("url");
        return rtspUrl;
    }


    public static String getPlaybackUrl(String cameraIndexCode,String alarmTime){
        /**
         * STEP1：设置平台参数，根据实际情况,
         * 设置host appkey appsecret 三个参数.
         * 摄像头ip：port
         */
        // 平台的ip端口
        ArtemisConfig.host = "10.168.192.31:443";
        // 密钥appkey
        ArtemisConfig.appKey = "28292616";
        // 密钥appSecret
        ArtemisConfig.appSecret = "gokGfaXduVFNHPvEAg6C";

        /**
         * STEP2：设置OpenAPI接口的上下文
         */
        final String ARTEMIS_PATH = "/artemis";

        /**
         * STEP3：设置接口的URI地址
         */
//        final String previewURLsApi = ARTEMIS_PATH + "/api/video/v2/cameras/previewURLs";

        final String playbackURLsApi = ARTEMIS_PATH + "/api/video/v2/cameras/playbackURLs";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                log.info("=========================== 访问现场地址  ===========================");
                log.info("=========================== https://" + playbackURLsApi +" ===========================");
                put("https://", playbackURLsApi);//根据现场环境部署确认是http还是https
            }
        };

        /**
         * STEP4：设置参数提交方式
         */
        String contentType = "application/json";


        /**
         * STEP5：组装请求参数
         */

        Map<String, String> intervalMap = getPlayBackInterval(alarmTime);

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("cameraIndexCode", cameraIndexCode);

        jsonBody.put("recordLocation", "0");
        jsonBody.put("protocol", "rtsp");
        jsonBody.put("transmode", 0);
        jsonBody.put("beginTime", intervalMap.get("formatStartPlaytime"));
        jsonBody.put("endTime", intervalMap.get("formatEndPlaytime"));
        jsonBody.put("expand", "streamform=rtp");
        String body = jsonBody.toJSONString();
        /**
         * STEP6：调用接口
         */
        log.info("===========================  调用摄像头平台入参：{}  ===========================",body);
        return ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, contentType , null);

    }


    /**
     * 获取告警的视频区间
     * @param inputDateTime 告警时间
     */
    public static Map<String,String> getPlayBackInterval(String inputDateTime) {
        HashMap<String, String> res = new HashMap<>(16);

        // 定义日期时间的输入格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 使用formatter解析字符串为LocalDateTime对象
        LocalDateTime alarmTime = LocalDateTime.parse(inputDateTime, formatter);

        //开始时间
        LocalDateTime startPlaytime = alarmTime.minusSeconds(5);
        LocalDateTime endPlaytime = alarmTime.plusSeconds(10);

        // 创建一个 DateTimeFormatter 对象，定义所需的格式
        DateTimeFormatter zoneFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        // 将 LocalDateTime 转换为 ZonedDateTime，添加时区信息（此处为东八区）
        ZonedDateTime zonedStartPlaytime = startPlaytime.atZone(ZoneId.of("Asia/Shanghai"));
        ZonedDateTime zonedEndPlaytime = endPlaytime.atZone(ZoneId.of("Asia/Shanghai"));
        // 格式化日期时间
        String formatStartPlaytime = zonedStartPlaytime.format(zoneFormatter);
        String formatEndPlaytime = zonedEndPlaytime.format(zoneFormatter);


        res.put("formatStartPlaytime",formatStartPlaytime);
        res.put("formatEndPlaytime",formatEndPlaytime);

        return res;
    }


}
